package com.oedtech.esl.service.eslService;

import com.oedtech.esl.model.esl.Ap;
import com.oedtech.esl.repository.esl.ApDao;
import com.oedtech.esl.repository.sys.StoreBsidDao;
import com.oedtech.esl.service.securityService.StoreService;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.net.InetSocketAddress;
import java.util.Date;
import java.util.List;

/**
 * @Author QiuLongYu
 * @Date 2019/7/30
 */
@Service
public class ApService {

    @Autowired
    private StoreBsidDao storeBsidDao;
    @Autowired
    private ApDao apDao;
    @Autowired
    private StoreService storeService;

    /**
     * 绑定基站与门店
     * @param mac
     * @param storeCode
     * @return
     */
    @Transactional
    public String bindApAndStoreCode(String mac,String storeCode){
        storeService.saveStore(storeCode);
        String apId=apDao.findApIdByMac(mac);
        if(apId==null)return "没有找到该基站";



        if(storeBsidDao.findCountByBsId(apId)>0){
            return "基站已经绑定门店，请先解绑";
        }
        storeBsidDao.saveNewRelate(storeCode, apId);
        return null;
    }


    /**
     * 解绑基站
     * @param mac
     * @return
     */
    @Transactional
    public String unbindApAndStoreCode(String mac){
        String apId=apDao.findApIdByMac(mac);
        storeBsidDao.deleteByApId(apId);
        return null;
    }

    public List<Ap> findAllAp(){
        List<Ap>apList=apDao.findAll();
        return apList;
    }


    /**
     * 保存ap状态
     * @param apid 基站id
     * @param channel  基站对应的netty channel
     * @param sz  基站握手数据 字节数组
     */
    @Transactional
    public void saveAp(String apid,Channel channel,byte[]sz){
        String apVersion=sz[10]+"."+sz[11]+"."+sz[12]+"."+sz[13];
        String apChannel=sz[14]+","+sz[15];
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<5;i++){
            sb.append(Integer.toHexString(sz[i+16]&0xff)).append(":");
        }
        sb.append(Integer.toHexString(sz[21]&0xff));
        String apMac=sb.toString();
        Ap ap = new Ap();
        ap.setApId(apid);
        ap.setStatus("online");
        ap.setChannel(apChannel);
        ap.setOnlineBeginTime(new Date());
        ap.setLastWorkTime(new Date());
        ap.setMac(apMac);
        ap.setVersion(apVersion);
        InetSocketAddress ipSocket = (InetSocketAddress)channel.remoteAddress();
        String ip = ipSocket.getAddress().getHostAddress();//获取客户端ip地址
        ap.setIp(ip);
        apDao.save(ap);

    }

    /**
     * 基站离线
     * @param apid
     */
    @Transactional
    public void apOffLine(String apid){
        apDao.apOffline(apid);
    }

    @Transactional
    public void deleteAp(String apid){
        apDao.deleteById(apid);
        storeBsidDao.deleteByApId(apid);
    }

}
